package com.ljsw.fragment;

import java.io.Serializable;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ljsw.activity.R;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.YuangongDialog;
import com.ljsw.entity.Emp;
import com.ljsw.entity.Person;
import com.ljsw.entity.RenWuClass;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.util.BitmapUtil;
import com.ljsw.util.DialogManager;
import com.ljsw.util.Table;

/**
 * 我的任务点击之后,进入的开始服务视图 作者: 石锚 版本: 1.0 日期: 2015-10-16
 */
public class StartFwFragment extends BaseFragment implements OnClickListener,
		OnTouchListener {
	private TextView back;// 返回
	private TextView shuaxin;// 刷新
	private DialogManager dmanager;
	private LoginDialog dialog;// 获取任务Dialog
	private YuangongDialog ygDialog; // 银行人员Dialog
	private DeleteDialog deleteDialog;
	private RenWuClass rw;
	private View view;
	private String str;// 输入车牌号接口返回的字符串
	private Handler handler;// 消息
	private String cid;// 车牌号
	private List<Emp> elist = new ArrayList<Emp>();// 保存银行员工信息集合
	private List<Person> plist = new ArrayList<Person>();// 企业人员集合 其实就2个
	Bitmap bmpleft, bmpright;
	Table[] tables;
	public final static int START_FUWU_TAG=2;
	Resources r;// 测试的时候用下
	// 开始服务的控件 派工单号 企业名称 封包方式 服务内容 联系人1 电话1 联系人2 电话2
	private TextView paigongId, qiyeName, fbfs, fwnr, lianxiren1, tel1,
			lianxiren2, tel2,
			// 线路信息 押运车牌号 上门服务地点 服务日期 服务时间 周转箱编号
			xianluxinxi, carId, fuwudidian, fuwudate, fuwutime, zzxbianhao,
			// 银行人员1-2 押运人员 开始服务
			yhry1, yhry2, yyry, startFuWu;
	private LinearLayout lay_bank;// 银行人员部分
	private LinearLayout lianxirenLayout;// 企业联系人
	private LinearLayout lianxitelLayout;// 企业联系人电话
	private MyRenwuFragment mfragment;
	private FragmentManager fm;
	private Bundle bundle;
	private Bitmap mapleft = null, mapright = null;
	private User user; // 押运员
	FragmentTransaction ft;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_ksfw, container, false);
		view.setOnTouchListener(this);
		// fm = getFragmentManager();
		ft = getFragmentManager().beginTransaction();
		dmanager = new DialogManager(getActivity());
		ygDialog = dmanager.getYuangongDialog();
		dialog = dmanager.getLoginDialog();
		deleteDialog = dmanager.getDeleteDialog();
		r = getActivity().getResources();// 模拟用(上线是会删除)
		App.getApp().back = "go";// 处理返回键的标识
		initView();
		bundle = getArguments();
		System.out.println("bundle"+bundle);
		rw = (RenWuClass) bundle.getSerializable("rw");
		cid = bundle.getString("cid");// 车牌号
		user = (User) bundle.getSerializable("user");
		mfragment = new MyRenwuFragment();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				dialog.dismiss();
				switch (msg.what) {
				case 0:
					// 视图显示
					showView();
					break;
				case 1:// 无信息返回
					OnClickLoad();
					deleteDialog.setTitle("获取信息失败");
					break;
				case 2:// 超时链接
					OnClickLoad();
					deleteDialog.setTitle("获取信息超时");
					break;
				case 3:// 系统异常
					OnClickLoad();
					deleteDialog.setTitle("获取信息异常");
					break;
				case 4:
					// 获取头像成功
					mapleft = BitmapUtil.stringToBitmap(str);// 字符串转成图片
					mapleft = BitmapUtil.compressBmpFromBmp(mapleft);// 图片压缩
					if (mapleft != null) {
						ygDialog.setHeadBitmap(mapleft);
					} else {
						ygDialog.setHeadBitmap(bmpleft);
					}
					break;
				case 5:
					// 获取头像失败继续获取图像
					getHeadImageLeft();
					break;
				case 6:
					// 获取头像成功
					mapright = BitmapUtil.stringToBitmap(str);// 字符串转成图片
					mapright = BitmapUtil.compressBmpFromBmp(mapright);// 图片压缩
					if (mapright != null) {
						ygDialog.setHeadBitmap(mapright);
					} else {
						ygDialog.setHeadBitmap(bmpright);
					}
					break;
				case 7:
					// 获取头像失败继续获取图像
					getHeadImageRight();
					break;
				case 8:

					ygDialog.setHeadBitmap(bmpleft);
					break;
				case 9:

					ygDialog.setHeadBitmap(bmpright);
					break;
				}
			}
		};
		return view;
	}

	/**
	 * 初始化控件
	 */
	public void initView() {
		bmpleft = BitmapFactory.decodeResource(r, R.drawable.nan);
		bmpright = BitmapFactory.decodeResource(r, R.drawable.nv);
		lianxirenLayout = (LinearLayout) view
				.findViewById(R.id.qiyelianxiren_layout);
		lianxitelLayout = (LinearLayout) view
				.findViewById(R.id.qiyelianxitel_layout);
		lay_bank = (LinearLayout) view.findViewById(R.id.lay_bank);// 银行人员部分
		paigongId = (TextView) view.findViewById(R.id.paigongId);// 派工单
		qiyeName = (TextView) view.findViewById(R.id.qiyeName);// 企业名称
		fbfs = (TextView) view.findViewById(R.id.fbfs);// 封包方式
		fwnr = (TextView) view.findViewById(R.id.fwnr);// 封包内容
		lianxiren1 = (TextView) view.findViewById(R.id.lianxiren1);// 企业联系人1
		tel1 = (TextView) view.findViewById(R.id.tel1);// 企业联系人电话1
		lianxiren2 = (TextView) view.findViewById(R.id.lianxiren2);// 企业联系人2
		tel2 = (TextView) view.findViewById(R.id.tel2);// 企业联系人电话2
		xianluxinxi = (TextView) view.findViewById(R.id.luxianxinxi);// 线路信息
		carId = (TextView) view.findViewById(R.id.carId);// 押运车牌号
		fuwudidian = (TextView) view.findViewById(R.id.sm_area);// 服务地址
		fuwudate = (TextView) view.findViewById(R.id.fw_date);// 服务日期
		fuwutime = (TextView) view.findViewById(R.id.fw_time);// 服务时间
		zzxbianhao = (TextView) view.findViewById(R.id.fw_zzxId);// 周转箱编号
		yhry1 = (TextView) view.findViewById(R.id.fw_bankry1);// 银行人员1
		yhry2 = (TextView) view.findViewById(R.id.fw_bankry2);// 银行人员2
		yyry = (TextView) view.findViewById(R.id.fw_yyry);// 押运人员
		startFuWu = (TextView) view.findViewById(R.id.startFuWu);// 开始服务确定
		back = (TextView) getActivity().findViewById(R.id.back);
		shuaxin = (TextView) getActivity().findViewById(R.id.shuaxin);
		shuaxin.setOnClickListener(this);
		back.setOnClickListener(this);
		back.setText("返回");
		startFuWu.setOnClickListener(this);
		yhry1.setOnClickListener(this);
		yhry2.setOnClickListener(this);

	}

	/**
	 * 给文本赋值
	 */
	public void setText() {
		if (rw != null) {
			if ("0".equals(rw.getType())) {
				fbfs.setText("半封包");
				// lay_bank.setVisibility(View.GONE);
			} else {
				fbfs.setText("全封包");
				// 影藏一些信息
				lay_bank.setVisibility(View.GONE);
			}
			if ("0".equals(rw.getService())) {
				fwnr.setText("上门收款");
			} else if ("1".equals(rw.getService())) {
				fwnr.setText("上门收单");
			} else if ("2".equals(rw.getService())) {
				fwnr.setText("上门送款");
			} else if ("3".equals(rw.getService())) {
				fwnr.setText("上门送单");
			}
			if ("1".equals(rw.getState())) {
				startFuWu.setVisibility(View.VISIBLE);
			} else {// 没有另任务 则不能进行下一步的业务
				startFuWu.setVisibility(View.GONE);
			}
			paigongId.setText(rw.getPaigongDan());
			fuwudidian.setText(rw.getAddress());
			qiyeName.setText(rw.getCompany());
			xianluxinxi.setText(rw.getLine());
			fuwudate.setText(rw.getDate());
			fuwutime.setText(rw.getStartTime() + "--" + rw.getEndTime());
			carId.setText(cid);
			yyry.setText("");
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		setText();
		load();
	}

	/**
	 * rw.getPaigongDan() rw.getType() 根据派工单 和 服务模式 获取信息
	 */
	public void load() {
		dialog.show();
		dialog.setMessage("获取信息明细...");
		new Thread(new Runnable() {
			public void run() {
				try {
					str = UpServer.getRenwuListMingXi(rw.getPaigongDan(),
							rw.getType());
					if (!"".equals(str) && null != str) {
						handler.sendEmptyMessage(0);// 成功
					} else {
						handler.sendEmptyMessage(1);// 没有任务
					}
				} catch (SocketException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(2);// 超时链接
				} catch (NullPointerException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(1);// 没有任务
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(3);// 其他异常
				}
			}
		}).start();
	}

	public void onClick(View arg0) {

		switch (arg0.getId()) {
		case R.id.startFuWu:// 切换fragment

			isCanService();
			break;
		case R.id.fw_bankry1:// 银行人员一点击
			showLeftEmp();
			break;
		case R.id.fw_bankry2:// 银行人员二点击
			showRightEmp();
			break;
		case R.id.back:
			/*
			 * bundle.putString("cid", cid); mfragment.setArguments(bundle);
			 * ft.addToBackStack(null); ft.replace(R.id.main_frame,
			 * mfragment).commit();
			 */
			if (getActivity() != null) {
				getActivity().onBackPressed();
			}
			break;
		case R.id.shuaxin:
			load();
			break;
		}
	}

	/**
	 * 
	 * @author 名字
	 * @Description: 替换到服务界面
	 * @throws
	 */
	private void skipStartFuwu() {
		bundle.putSerializable("rw", (Serializable) rw);
		bundle.putString("cid", cid);
		bundle.putSerializable("plist", (Serializable) plist);
		bundle.putSerializable("userList", (Serializable) elist);
		bundle.putSerializable("user", user);
		mCallback.onArticleSelected(KssmFragment.KSSM_TAG, bundle, StartFwFragment.this);
	}

	/**
	 * 
	 * @author 名字
	 * @Description: 判断该派工单是否可用
	 * @throws
	 */
	private void isCanService() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					final String result = UpServer.upCkRenWuState(paigongId
							.getText().toString(), "" + App.getApp().userZhanghao);
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if ("success".equals(result)) {
								skipStartFuwu();
							} else if ("error".equals(result)) {
								DeleteDialog dialog = new DeleteDialog(
										getActivity()).builder();
								dialog.setTitle("当前任务已被撤销..");
								dialog.setOnlyButton();
								dialog.setPositiveButton("确定",
										new OnClickListener() {

											@Override
											public void onClick(View arg0) {
												getActivity().onBackPressed();
											}
										});
								dialog.show();
								startFuWu.setVisibility(View.GONE);
							}
						}
					});

				} catch (Exception e) {
					e.printStackTrace();
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getActivity(), "服务器或网络异常..",
									Toast.LENGTH_LONG).show();
						}
					});
				}

			}
		}).start();
	}

	/**
	 * 确定点击事件 取消
	 */
	public void quxiao() {
		deleteDialog.setNegativeButton("取消", new OnClickListener() {
			public void onClick(View arg0) {
			}
		});
	}

	/**
	 * 领取任务失败重试
	 */
	public void OnClickLoad() {
		deleteDialog.show();
		deleteDialog.setPositiveButton("确定", new OnClickListener() {
			public void onClick(View arg0) {
				load();
			}
		});
		quxiao();
	}

	/**
	 * 视图显示
	 */
	public void showView() {
		plist.clear();
		elist.clear();
		tables = Table.doParse(str);
		List<String> list = tables[0].get("qiyelianxiren").getValues();// 企业联系人名集合
		for (int i = 0; i < list.size(); i++) {
			System.out.println("名字：=" + list.get(i));
			Person p = new Person();
			p.setName(list.get(i));
			// p.setPid(tables[0].get("qiyeid").getValues().get(i));
			p.setPid(tables[0].get("qiyelianxirenid").getValues().get(i));
			System.out.println("企业人员：=" + p.getPid());
			p.setTel(tables[0].get("qiyelianxiDianhua").getValues().get(i));
			plist.add(p);
		}
		rw.setPlist(plist);// 得到企业人员信息 只有2个企业人员
		if (plist.size() == 1) {
			lianxiren1.setText(plist.get(0).getName());
			tel1.setText(plist.get(0).getTel());
			lianxirenLayout.setVisibility(View.GONE);
			lianxitelLayout.setVisibility(View.GONE);
		} else if (plist.size() == 2) {
			lianxiren1.setText(plist.get(0).getName());
			tel1.setText(plist.get(0).getTel());
			lianxiren2.setText(plist.get(1).getName());
			tel2.setText(plist.get(1).getTel());
		}
		// 获取银行员工的信息 shengfenzheng
		
		List<String> clist = tables[1].get("gonghao").getValues();
		for (int i = 0; i < clist.size(); i++) {
			Emp emp = new Emp();// 银行员工
			emp.setUrlImage(tables[1].get("userphoto").getValues().get(i));
			System.out.println("图片地址：="
					+ tables[1].get("userphoto").getValues().get(i));
			emp.setNum(clist.get(i));
			emp.setCard(tables[1].get("shengfenzheng").getValues().get(i));
			emp.setName(tables[1].get("yayunyuan").getValues().get(i));
			emp.setOrganization(tables[1].get("jigouming").getValues().get(i));
			emp.setJigouId(tables[1].get("jigouid").getValues().get(i));
			elist.add(emp);
		}
		if (elist.size() == 1) {// 一个人
			yhry1.setText(elist.get(0).getName());
			yhry1.setEnabled(true);
			yhry2.setVisibility(View.GONE);
		} else if (elist.size() == 2) {
			yhry1.setText(elist.get(0).getName());
			yhry2.setText(elist.get(1).getName());
			yhry1.setEnabled(true);
			yhry2.setEnabled(true);
			yhry2.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 显示左边银行人员
	 */
	public void showLeftEmp() {
		ygDialog.show();
		ygDialog.setDanweiName(elist.get(0).getOrganization());// 机构名
		ygDialog.setGonghao(elist.get(0).getNum());
		ygDialog.setYgname(elist.get(0).getName());
		ygDialog.setShenfenzheng(elist.get(0).getCard());
		if (elist.get(0).getUrlImage().equals("one")) {// 接口返回的处理值

			ygDialog.setHeadBitmap(bmpleft);
		} else {
			if (mapleft == null) {
				getHeadImageLeft();
			} else {
				ygDialog.setHeadBitmap(mapleft);
			}
		}
	}

	/**
	 * 显示右边银行人员信息
	 */
	public void showRightEmp() {
		ygDialog.show();
		ygDialog.setDanweiName(elist.get(1).getOrganization());// 机构名
		ygDialog.setGonghao(elist.get(1).getNum());// 工号
		ygDialog.setYgname(elist.get(1).getName());// 员工姓名
		ygDialog.setShenfenzheng(elist.get(1).getCard());// 身份证
		if (elist.get(1).getUrlImage().equals("two")) {// 接口返回的处理值
			ygDialog.setHeadBitmap(bmpright);
		} else {
			if (mapright == null) {
				getHeadImageRight();
			} else {
				ygDialog.setHeadBitmap(mapright);
			}
		}
	}

	/**
	 * 获取任务头像左
	 */
	public void getHeadImageLeft() {
		new Thread(new Runnable() {
			public void run() {
				try {
					str = UpServer.upImgShow(elist.get(0).getUrlImage());
					System.out.println("str:=" + str);
					if (!"".equals(str) && null != str) {
						handler.sendEmptyMessage(4);
					} else {
						handler.sendEmptyMessage(8);
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(5);
				}
			}
		}).start();
	}

	/**
	 * 获取任务头像右
	 */
	public void getHeadImageRight() {
		new Thread(new Runnable() {
			public void run() {
				try {
					str = UpServer.upImgShow(elist.get(1).getUrlImage());
					if (!"".equals(str) && null != str) {
						handler.sendEmptyMessage(6);
					} else {
						handler.sendEmptyMessage(9);
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(7);
				}

			}
		}).start();
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return true;
	}
}
